<?php
// 启用错误显示（仅用于调试）
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 捕获所有输出
ob_start();

// 设置JSON响应头
header('Content-Type: application/json');

// 加载必要文件
try {
    session_start();
    require_once '../config/database.php';
    require_once '../includes/functions.php';
} catch (Exception $e) {
    ob_end_clean();
    echo json_encode([
        'success' => false,
        'message' => '服务器配置错误',
        'error' => $e->getMessage()
    ]);
    exit;
}

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];

// 简化参数获取 - 统一处理POST和JSON
try {
    // 优先使用POST参数
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = $_POST['payment_method'] ?? '';
    
    // 如果POST为空，尝试JSON
    if ($amount == 0 || empty($payment_method)) {
        $input = json_decode(file_get_contents('php://input'), true);
        if (!empty($input)) {
            $amount = floatval($input['amount'] ?? $amount);
            $payment_method = $input['payment_method'] ?? $payment_method;
        }
    }
} catch (Exception $e) {
    error_log("参数解析错误: " . $e->getMessage());
}

try {
    // 简化验证逻辑
    if ($amount <= 0) {
        throw new Exception('充值金额必须大于0');
    }
    
    if (empty($payment_method)) {
        throw new Exception('请选择支付方式');
    }
    
    if ($amount < 1) {
        throw new Exception('最低充值金额为¥1');
    }
    
    if ($amount > 50000) {
        throw new Exception('单次充值不能超过¥50,000');
    }
    
    // 生成4位随机码
    $random_code = sprintf('%04d', mt_rand(1000, 9999));
    
    // 简化表检查 - 假设表已经存在
    // 如果表不存在，后续的INSERT会失败并被捕获
    
    // 简单直接地插入记录
    $stmt = $pdo->prepare("
        INSERT INTO deposit_records (user_id, amount, payment_method, random_code, status, created_at) 
        VALUES (?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt->execute([$user_id, $amount, $payment_method, $random_code]);
    
    $deposit_id = $pdo->lastInsertId();
    
    if (!$deposit_id) {
        throw new Exception('创建充值记录失败');
    }
    
    // 清理缓冲区
    ob_end_clean();
    
    // 返回成功响应
    echo json_encode([
        'success' => true,
        'message' => '充值申请已创建',
        'deposit_id' => $deposit_id,
        'random_code' => $random_code,
        'amount' => $amount
    ]);
    
} catch (Exception $e) {
    // 记录错误
    error_log("充值失败: " . $e->getMessage());
    
    // 清理缓冲区
    ob_end_clean();
    
    // 返回错误响应
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

// 确保脚本结束
exit;
?>
